//
//  HJEaseManager.m
//  Sneakers
//
//  Created by 胡光健 on 2017/10/13.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HJEaseManager.h"

@implementation HJEaseManager

+ (NSString *)easeMobUserNameWithPhone:(NSString *)phone {
    NSString *userName;
    if (phone.length < 11) {
        NSLog(@"环信账号错误"); return @"";
    }
    userName = [NSString stringWithFormat:@"%@",phone];
    return userName;
}

+ (void)loginWithCompletion:(void (^)(BOOL success))completion {
    HJUserModel *model = [HJUserManager getUserModel];
    // 异步登陆账号
//    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:model.mobile password:@"SN123456"];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                // 设置是否自动登录
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                // 获取数据库中数据
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient] migrateDatabaseToLatestSDK];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSLog(@"环信登录成功");
                        [[EMClient sharedClient] setApnsNickname:model.nickname];
                        [[EMClient sharedClient] updatePushOptionsToServer];
                        // 发送自动登陆状态通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
                        if (completion) {
                            completion(YES);
                        }
                    });
                });
            } else {
                switch (error.code) {
                    case EMErrorNetworkUnavailable:
                        [[UIViewController currentViewController] showHint:@"网络连接失败"];
                        break;
                    case EMErrorServerNotReachable:
                         [[UIViewController currentViewController] showHint:@"连接服务器失败"];
                        break;
                    case EMErrorUserAuthenticationFailed:
                        [[UIViewController currentViewController] showHint:@"验证失败"];
                        break;
                    case EMErrorServerTimeout:
                        [[UIViewController currentViewController] showHint:@"连接超时"];
                        break;
                    case EMErrorServerServingForbidden:
                        [[UIViewController currentViewController] showHint:@"服务器拒绝访问"];
                        break;
                    default:
                        [[UIViewController currentViewController] showHint:@"登录失败"];
                        break;
                }
                if (completion) {
                    completion(NO);
                }
            }
        });
    });
}


#pragma mark - 注销环信登录

+ (void)logout {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        EMError *error = [[EMClient sharedClient] logout:YES];
        if (!error) {
            NSLog(@"环信退出成功");
            [mNotificationCenter postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
        }
    });
}
#pragma mark -- 注册客服
+ (void)registerWithHErrorCompletion:(void (^)(BOOL success))completion {
    HJUserModel *model = [HJUserManager getUserModel];
    HError *error = [[HChatClient sharedClient] registerWithUsername:model.mobile password:@"SN123456"];
//    if (error.code) {
//        switch (error.code) {
//            case HErrorNetworkUnavailable:
//                [[UIViewController currentViewController] showHint:@"网络不可用"];
//                break;
//            case HErrorUserAlreadyExist:
//                [[UIViewController currentViewController] showHint:@"用户已存在"];
//                break;
//            case HErrorUserAuthenticationFailed:
//                [[UIViewController currentViewController] showHint:@"无开放注册权限"];
//                break;
//            case HErrorUserIllegalArgument:
//                [[UIViewController currentViewController] showHint:@"用户名非法"];
//                break;
//            default:
//                [[UIViewController currentViewController] showHint:@"登录失败"];
//                break;
//        }
//    }
    NSLog(@"客服注册13成功");
}
// 三方登录生成随机账号
+(NSString *)random {
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    NSString* strTime = [NSString stringWithFormat:@"%0.f",timeStamp];
    
    int value = arc4random();
    NSString *random = [strTime stringByAppendingString:[NSString stringWithFormat:@"%zd",value]];
    [mUserDefaults setObject:random forKey:@"random"];
    return random;
}
+(void)loginChatClientWithCompletion:(void (^)(BOOL success))completion {
    HJUserModel *model = [HJUserManager getUserModel];
    HChatClient *client = [HChatClient sharedClient];
    if ([model.is_register isEqualToString:@"0"]) {
        [client registerWithUsername:[self random] password:@"SN123456"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [client loginWithUsername:[mUserDefaults objectForKey:@"random"] password:@"SN123456"];
        });
    }else {
        [client registerWithUsername:model.mobile password:@"SN123456"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (client.isLoggedInBefore != YES) {
                HError *error = [client loginWithUsername:model.mobile password:@"SN123456"];
                if (!error) {
                    //登录成功
                    NSLog(@"客服登录成功");
                    if (completion) {
                        completion(YES);
                    }
                } else { //登录失败
                    if (completion) {
                        completion(NO);
                    }
                }
            }
        });
    }
}
+(void)loginOut {
    
    HError *error = [[HChatClient sharedClient] logout:YES];
    if (error) { //登出出错
    } else {//登出成功
    }
}
@end
